﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using Waiter.Common;
using Waiter.DataLayer;

namespace Waiter.Controler
{
    class MasterCtrl
    {

        #region data access methods
        /// <summary>
        /// Phương thức get danh sách các group trong MASTER.
        /// </summary>
        /// <returns></returns>
        public List<VIEW_MasterGroup_ComboBox> fsGetListGroup()
        {
            List<VIEW_MasterGroup_ComboBox> groupList = new List<VIEW_MasterGroup_ComboBox>();
            VIEW_MasterGroup_ComboBox tempItemList = new VIEW_MasterGroup_ComboBox();
            List<String> strGroupList = new List<string>();

            try
            {
                var resultList = (from p in Common.CommonGlobalVariable.globalDataContext.MASTERs
                                    select new
                                    {
                                        p.GROUP_CODE,
                                        p.GROUP_NAME,
                                        p.CAN_ADD_NEW
                                    }).ToList();

                strGroupList = resultList.Select(x => x.GROUP_CODE).Distinct().ToList();     

                for (int i = 0; i < strGroupList.Count; i++)
	            {
                    for (int j = 0; j < resultList.Count; j++)
			        {
                        if (strGroupList[i].Equals(resultList[j].GROUP_CODE))
	                    {
		                    tempItemList = new VIEW_MasterGroup_ComboBox();
                            tempItemList.CODE = resultList[j].GROUP_CODE;
                            tempItemList.NAME = resultList[j].GROUP_NAME;
                            tempItemList.CAN_ADD_NEW = resultList[j].CAN_ADD_NEW;
                            groupList.Add(tempItemList);
                            break;
	                    }
			        }
	            }

                return groupList;  
            }
            catch (Exception ex)
            {
                CommonLogging.fsWriteLog(CommonConstants.LOG_TYPE_ERROR,
                    "MasterCtrl.fsGetListGroup",
                    "",
                    ex.ToString());
                return null;
            }
        }

        /// <summary>
        /// Phương thức load data danh mục MASTER vào combobox
        /// </summary>
        /// <param name="cmb"></param>
        /// <returns></returns>
        public ResultStatus fsLoadCmbGroupList(ComboBox cmb)
        {
            List<ComboboxItem> cmbDataSource = new List<ComboboxItem>();
            try
            {
                // remove old items
                cmb.Items.Clear();
                // get data
                List<VIEW_MasterGroup_ComboBox> masterList = fsGetListGroup();
                //if (masterList != null && masterList.Count != 0)
                //{
                //    foreach (VIEW_MasterGroup_ComboBox item in masterList)
                //    {
                //        ComboboxItem cmbItem = new ComboboxItem();
                //        cmbItem.Text = item.NAME;
                //        cmbItem.Value = item.CODE;

                //        cmbDataSource.Add(cmbItem);
                //    }
                //}
                cmb.DataSource = masterList;
                cmb.ValueMember = "CODE";
                cmb.DisplayMember = "NAME";

                //cmb.DisplayMember = CommonConstants.CMB_TEXT;
                //cmb.ValueMember = CommonConstants.CMB_VALUE;
                //cmb.DataSource = cmbDataSource;
                
            }
            catch (Exception ex)
            {
                CommonLogging.fsWriteLog(CommonConstants.LOG_TYPE_ERROR,
                    "MasterCtrl.fsLoadCmbGroupList",
                    "",
                    ex.ToString());
                return ResultStatus.ERROR;
            }

            if (cmbDataSource.Count == 0)
            {
                return ResultStatus.NONE;
            }
            return ResultStatus.SUCCESS;
        }


        /// <summary>
        /// Phương thức load data danh mục MASTER (theo  group) vào combobox
        /// </summary>
        /// <param name="cmb"></param>
        /// <returns></returns>
        public ResultStatus fsLoadCmbGroupList(ComboBox cmb, string groupCode, ComboboxItem defaultItem)
        {
            List<ComboboxItem> cmbDataSource = new List<ComboboxItem>();
            if (defaultItem != null)
            {
                cmbDataSource.Add(defaultItem);
            }
            try
            {
                // get data
                List<MASTER> masterList = fsGetMasterFromGroupCode(groupCode);
                if (masterList != null && masterList.Count != 0)
                {
                    foreach (MASTER item in masterList)
                    {
                        ComboboxItem cmbItem = new ComboboxItem();
                        cmbItem.Text = item.VALUE;
                        cmbItem.Value = item.KEY_CODE;

                        cmbDataSource.Add(cmbItem);
                    }
                }

                cmb.DisplayMember = CommonConstants.CMB_TEXT;
                cmb.ValueMember = CommonConstants.CMB_VALUE;
                cmb.DataSource = cmbDataSource;

            }
            catch (Exception ex)
            {
                CommonLogging.fsWriteLog(CommonConstants.LOG_TYPE_ERROR,
                    "MasterCtrl.fsLoadCmbGroupList",
                    CommonUtils.fsParamListToString(new object[2] { groupCode, defaultItem}),
                    ex.ToString());
                return ResultStatus.ERROR;
            }

            if (cmbDataSource.Count == 0)
            {
                return ResultStatus.NONE;
            }
            return ResultStatus.SUCCESS;
        }

        /// <summary>
        /// Phương thức load danh sách MASTER theo GROUP_CODE
        /// </summary>
        /// <param name="pGroupCode"></param>
        /// <returns></returns>
        public List<MASTER> fsGetMasterFromGroupCode(string pGroupCode)
        {
            List<MASTER> lsResult = new List<MASTER>();
            try
            {
                lsResult = (from s in Common.CommonGlobalVariable.globalDataContext.MASTERs
                            where s.GROUP_CODE == pGroupCode
                               && s.DEL_FLG == false   
                            orderby s.VALUE ascending
                            select s).ToList<MASTER>();

                return lsResult;
            }
            catch (Exception ex)
            {
                CommonLogging.fsWriteLog(CommonConstants.LOG_TYPE_ERROR,
                    "MasterCtrl.fsGetMasterFromGroupCode",
                    CommonUtils.fsParamListToString(new object[1] { pGroupCode}),
                    ex.ToString());
                return null;
            }
        }

        /// <summary>
        /// Phương thức lay item master theo goupcode va keycode
        /// </summary>
        /// <param name="pGroupCode"></param>
        /// <param name="keyCode"></param>
        /// <returns></returns>
        public MASTER fsGetMasterFromGroupCode(string pGroupCode, string keyCode)
        {
            try
            {
                MASTER item = CommonGlobalVariable.globalDataContext.MASTERs
                    .First(s => s.GROUP_CODE == pGroupCode 
                        && s.DEL_FLG == false
                        && s.KEY_CODE == keyCode);

                return item;
            }
            catch (Exception ex)
            {
                CommonLogging.fsWriteLog(CommonConstants.LOG_TYPE_ERROR,
                    "MasterCtrl.fsGetMasterFromGroupCode",
                    CommonUtils.fsParamListToString(new object[2] { pGroupCode, keyCode }),
                    ex.ToString());
                return null;
            }
        }

        public string fsGetMasterValue(string pGroupCode, string keyCode)
        {
            MASTER item = fsGetMasterFromGroupCode(pGroupCode, keyCode);
            if (item == null)
                return string.Empty;

            return item.VALUE;
        }

        /// <summary>
        /// Kiểm tra xem trị tại 1 group đã tồn tại hay chưa (không kể các trị đã bị xóa)
        /// </summary>
        /// <param name="pID">Code</param>
        /// <param name="pGroupCode">Code nhóm</param>
        /// <param name="pValue">giá trị cần kiểm tra</param>
        /// <returns></returns>
        public bool fsCheckExistValue(string pID, string pGroupCode, string pValue)
        {
            List<MASTER> lsResult = new List<MASTER>();

            try
            {
                if (pID == string.Empty)//Điều kiện MASTER.CODE = String.Empty thì loại bỏ điều kiện này.
                {

                    lsResult = (from s in CommonGlobalVariable.globalDataContext.MASTERs
                                where s.GROUP_CODE == pGroupCode
                                   && s.VALUE == pValue
                                   && s.DEL_FLG == false
                                select s).ToList<MASTER>();
                }
                else
                {
                    lsResult = (from s in CommonGlobalVariable.globalDataContext.MASTERs
                                where s.VALUE == pValue
                                   && s.DEL_FLG == false
                                   && s.CODE == pID
                                select s).ToList<MASTER>();
                }

                if (lsResult.Count > 0)
                {
                    return true;
                }
                else
                {
                    return false;
                }
            }
            catch (Exception ex)
            {
                CommonLogging.fsWriteLog(CommonConstants.LOG_TYPE_ERROR,
                    "MasterCtrl.fsCheckExistValue",
                    CommonUtils.fsParamListToString(new object[3] { pID, pGroupCode, pValue}),
                    ex.ToString());
                return true;                
            }            
        }

        /// <summary>
        /// Kiểm tra xem trị tại 1 group đã tồn tại hay chưa (chỉ gồm các item bị xóa)
        /// </summary>
        /// <param name="pID">Code</param>
        /// <param name="pGroupCode">Code nhóm</param>
        /// <param name="pValue">giá trị cần kiểm tra</param>
        /// <returns></returns>
        public bool fsCheckExistValue2(string pID, string pGroupCode, string pValue)
        {
            List<MASTER> lsResult = new List<MASTER>();

            try
            {
                if (pID == string.Empty)//Điều kiện MASTER.CODE = String.Empty thì loại bỏ điều kiện này.
                {

                    lsResult = (from s in CommonGlobalVariable.globalDataContext.MASTERs
                                where s.GROUP_CODE == pGroupCode
                                   && s.VALUE == pValue
                                   && s.DEL_FLG == true
                                select s).ToList<MASTER>();
                }
                else
                {
                    lsResult = (from s in CommonGlobalVariable.globalDataContext.MASTERs
                                where s.VALUE == pValue
                                   && s.DEL_FLG == true
                                   && s.CODE == pID
                                select s).ToList<MASTER>();
                }

                if (lsResult.Count > 0)
                {
                    return false;
                }
                else
                {
                    return true;
                }
            }
            catch (Exception ex)
            {
                CommonLogging.fsWriteLog(CommonConstants.LOG_TYPE_ERROR,
                    "MasterCtrl.fsCheckExistValue2",
                    CommonUtils.fsParamListToString(new object[3] { pID, pGroupCode, pValue }),
                    ex.ToString());
                return true;
            }
        }

        /// <summary>
        /// Kiểm tra xem trị tại 1 group đã tồn tại hay chưa (chỉ gồm các item bị xóa)
        /// </summary>
        /// <param name="pID">Code</param>
        /// <param name="pGroupCode">Code nhóm</param>
        /// <param name="pValue">giá trị cần kiểm tra</param>
        /// <returns></returns>
        public bool fsUnDelete(string pID, string pGroupCode, string pValue)
        {
            MASTER resultMaster = new MASTER();

            try
            {
                if (pID == string.Empty)//Điều kiện MASTER.CODE = String.Empty thì loại bỏ điều kiện này.
                {
                    resultMaster = CommonGlobalVariable.globalDataContext.MASTERs.FirstOrDefault(x => x.GROUP_CODE == pGroupCode & x.VALUE == pValue & x.DEL_FLG == true);
                }
                else
                {
                    resultMaster = CommonGlobalVariable.globalDataContext.MASTERs.FirstOrDefault(x => x.VALUE == pValue & x.DEL_FLG == true & x.CODE == pID);
                }


                if (resultMaster.CODE != String.Empty)
                {
                    resultMaster.DEL_FLG = false;
                    CommonGlobalVariable.globalDataContext.SubmitChanges();
                    return true;
                }

                return false;
            }
            catch (Exception ex)
            {
                CommonLogging.fsWriteLog(CommonConstants.LOG_TYPE_ERROR,
                    "MasterCtrl.fsUnDelete",
                    CommonUtils.fsParamListToString(new object[3] { pID, pGroupCode, pValue }),
                    ex.ToString());
                return true;
            }
        }

        /// <summary>
        /// Thêm mới data vào bảng MASTER
        /// </summary>
        /// <param name="pCode"></param>
        /// <param name="pGroupCode"></param>
        /// <param name="pGroupName"></param>
        /// <param name="pKeyCode"></param>
        /// <param name="pValue"></param>
        /// <param name="pIsDel"></param>
        /// <param name="pOPID"></param>
        /// <param name="pAddDate"></param>
        /// <param name="pUpdDate"></param>
        /// <returns></returns>
        public bool fsInsertData(string pCode, string pGroupCode, string pGroupName, string pKeyCode, string pValue, bool pIsDel, string pOPID, DateTime pAddDate, DateTime pUpdDate)
        {
            //Tạo mới item và add vào DataContext
            MASTER addMaster = new MASTER();
            try
            {
                addMaster.CODE = pCode;
                addMaster.CAN_ADD_NEW = true;
                addMaster.GROUP_CODE = pGroupCode;
                addMaster.GROUP_NAME = pGroupName;
                addMaster.KEY_CODE = pKeyCode;
                addMaster.VALUE = pValue;
                addMaster.DEL_FLG = pIsDel;
                addMaster.OPID = pOPID;
                addMaster.ADD_DATE = pAddDate;
                addMaster.UPD_DATE = pUpdDate;

                CommonGlobalVariable.globalDataContext.MASTERs.InsertOnSubmit(addMaster);
                CommonGlobalVariable.globalDataContext.SubmitChanges();

                return true;
            }
            catch (Exception ex)
            {
                CommonLogging.fsWriteLog(CommonConstants.LOG_TYPE_ERROR,
                    "MasterCtrl.fsInsertData",
                    CommonUtils.fsParamListToString(new object[1] { addMaster }),
                    ex.ToString());
                return false;
            }
        }

        /// <summary>
        /// Delete một dòng data tại bảng MASTER
        /// </summary>
        /// <param name="pID">code dòng cần xóa</param>
        /// <returns></returns>
        public bool fsDeleteMasterItem(string pID, DateTime pUpdDate, string pOPID)
        {
            if (pID == String.Empty & pID.Length != 12)
            {
                return false;
            }
            else
            {
                try
                {
                    MASTER updItem = CommonGlobalVariable.globalDataContext.MASTERs.SingleOrDefault(x => x.CODE == pID);

                    //Kiểm tra trong trường hợp updItem = default.
                    if (updItem.CODE == String.Empty)
                    {
                        //Trong trường hợp không có data SingleOrDefault sẽ trả về trị mặc định của kiểu dữ liệu.
                        return false;
                    }

                    updItem.DEL_FLG = true;
                    updItem.UPD_DATE = pUpdDate;
                    updItem.OPID = pOPID;
                    CommonGlobalVariable.globalDataContext.SubmitChanges();

                    return true;
                }
                catch (Exception ex)
                {
                    CommonLogging.fsWriteLog(CommonConstants.LOG_TYPE_ERROR,
                    "MasterCtrl.fsDeleteMasterItem",
                    CommonUtils.fsParamListToString(new object[3] { pID, pUpdDate, pOPID }),
                    ex.ToString());
                    return false;
                }
            }
        }

        /// <summary>
        /// tao moi hoac cap nhat gia tri 
        /// </summary>
        /// <returns></returns>
        public ResultStatus fsInsertOrUpdateSingle(string groupCode, string groupName, string keycode, string value)
        {
            try
            {
                MASTER item = CommonGlobalVariable.globalDataContext.MASTERs.FirstOrDefault(q => q.GROUP_CODE == groupCode && q.KEY_CODE == keycode);
                if (item != null)
                {
                    item.VALUE = value;
                    item.OPID = CommonUtils.fsGetOPID();
                    item.UPD_DATE = DateTime.Now;
                }
                else
                {
                    item = new MASTER();
                    item.CODE = CommonUtils.fsCreateNewCode();
                    item.GROUP_CODE = groupCode;
                    item.GROUP_NAME = groupName;
                    item.KEY_CODE = keycode;
                    item.VALUE = value;
                    item.OPID = CommonUtils.fsGetOPID();
                    item.UPD_DATE = DateTime.Now;
                    item.ADD_DATE = DateTime.Now;
                    item.DEL_FLG = CommonConstants.FLAG_OFF;
                    CommonGlobalVariable.globalDataContext.MASTERs.InsertOnSubmit(item);
                }

                CommonGlobalVariable.globalDataContext.SubmitChanges();
            }
            catch (Exception ex)
            {
                CommonLogging.fsWriteLog(CommonConstants.LOG_TYPE_ERROR,
                    "MasterCtrl.fsDeleteMasterItem",
                    CommonUtils.fsParamListToString(new object[4] { groupCode, groupName, keycode, value }),
                    ex.ToString());
                return ResultStatus.ERROR;
            }
            return ResultStatus.SUCCESS;
        }
        
        #endregion

        #region logic methods
        /// <summary>
        /// load data cho combobox quyen su dung he thong
        /// </summary>
        public ResultStatus fsLoadCmbType(ComboBox cmb)
        {
            List<ComboboxItem> cmbDataSource = new List<ComboboxItem>();
            try
            {
                // remove old items
                cmb.Items.Clear();
                // get data
                List<MASTER> masterList = fsGetMasterFromGroupCode(CommonConstants.MASTER_USER_TYPE);
                if (masterList != null && masterList.Count != 0)
                {
                    foreach (MASTER item in masterList)
                    {
                        ComboboxItem cmbItem = new ComboboxItem();
                        cmbItem.Text = item.VALUE;
                        cmbItem.Value = item.KEY_CODE;

                        cmbDataSource.Add(cmbItem);
                    }
                }

                cmb.DisplayMember = CommonConstants.CMB_TEXT;
                cmb.ValueMember = CommonConstants.CMB_VALUE;
                cmb.DataSource = cmbDataSource;

            }
            catch (Exception ex)
            {
                CommonLogging.fsWriteLog(CommonConstants.LOG_TYPE_ERROR,
                    "MasterCtrl.fsLoadCmbType",
                    "",
                    ex.ToString());
                return ResultStatus.ERROR;
            }
            if (cmbDataSource.Count == 0)
            {
                return ResultStatus.NONE;
            }
            return ResultStatus.SUCCESS;
        }
        #endregion
    }
}
